package scau.mis4.chanyulin.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import scau.mis4.chanyulin.base.common.BaseController;
import scau.mis4.chanyulin.entity.BarCode;
import scau.mis4.chanyulin.service.IBarCodeService;
import java.util.List;

/**
 * Created by cyl on 2018/03/27.
 * BarCode Controller层
 */
@RestController
@RequestMapping("/barcode")
public class BarCodeController extends BaseController {

    @Autowired
    private IBarCodeService barCodeService;

    /**
     * 添加BarCode
     * @param barCode
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public String addBarCode(BarCode barCode) throws Exception {
        barCodeService.add(barCode);
        return createSuccessJSON();
    }

    /**
     * 删除某个BarCode
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public String deleteBarCodeById(String id) throws Exception {
        barCodeService.delete(id);
        return createSuccessJSON();
    }

    /**
     * 查找某个BarCode
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/get")
    public String getBarCodeById(String id) throws Exception {
        BarCode barCode = barCodeService.findByKey(id);
        Model model = new ExtendedModelMap().addAttribute("result", barCode);
        return createSuccessJSON(model);
    }

    /**
     * 获取全部BarCode
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public String listAllBarCode() throws Exception {
        List<BarCode> barCodeList = barCodeService.findAll();
        Model model = new ExtendedModelMap().addAttribute("result",barCodeList);
        return createSuccessJSON(model);
    }

    /**
     * 分页查询BarCode
     * @param pageNum 页码
     * @param pageSize 每页数据数量
     * @return
     * @throws Exception
     */
    @PostMapping("/page")
    public String listBarCodeByPage(int pageNum, int pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        List<BarCode> barCodeList = barCodeService.findAll();
        PageInfo<BarCode> pageInfo = new PageInfo<>(barCodeList);
        Model model = new ExtendedModelMap()
                .addAttribute("result", barCodeList)
                .addAttribute("pageInfo", pageInfo);
        return createSuccessJSON(model);
    }

    /**
     * 更新某个BarCode
     * @param barCode
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    public String updateBarCodeById(BarCode barCode) throws Exception {
        barCodeService.updateById(barCode);
        return createSuccessJSON();
    }

}
